// vip/buy_vip.js
const api = require("../request/api")
const request = require("../request/request")
const util = require("../utils/util")
const App = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0';

Page({

    /**
     * 页面的初始数据
     */
    data: {
        barHeight: App.globalData.paddingTop,

        avatarUrl: defaultAvatarUrl,
        uid: '',
        user_name: '请点击登录',
        userInfo: {},
        fullUserInfo: {},
        mobile: '',
        isVip: false,
        openId: '',
        islogin: false,

        // 协议勾选标识
        if_read: false,
        chosen_index: 2,
        amount: 38.8,
        vipGoodId: 110,

        styledata: {
            "bg_color": "#fff",
            "color": "#000",
            "leftflag": true,
            "homeflag": true,
            "name": "会员充值"
        },

        visible: false,

        combo_list: [{
            title: '月卡   (30天)',
            price: 3.8,
            originPrice: '10.00',
            goodId: 110,
            buytip: '3.80',
            discount: ' 88折',
        }, {
            title: '季卡   (90天)',
            price: 8.8,
            originPrice: '20.00',
            goodId: 111,
            buytip: '8.80',
            discount: ' 85折',
        },
        {
            title: '年卡   (365天)',
            price: 38.8,
            originPrice: '50.00',
            goodId: 112,
            buytip: '38.80',
            discount: ' 8折',
        }
        ]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        const { chosenid, from } = options
        let combo_list = this.data.combo_list

        // 保存上一个页面来源
        this.from = from

        // 预先携带了充值会员的序号
        if (chosenid == 0 || chosenid) {
            this.setData({
                chosen_index: parseInt(chosenid),
                amount: combo_list[parseInt(chosenid)]['price'],
                vipGoodId: combo_list[parseInt(chosenid)]['goodId']
            })
        } else {
            this.setData({
                chosen_index: parseInt(2),
                amount: combo_list[parseInt(2)]['price'],
                vipGoodId: combo_list[parseInt(2)]['goodId']
            })
        }
        console.log("from", from);
        console.log(this.data.chosen_index, this.data.amount, this.data.vipGoodId);
        this.init_data()
        this.get_address_list()

        // let fulluserInfo = App.globalData.fulluserInfo
        // let userInfo = App.globalData.userInfo
        // console.log(fulluserInfo, userInfo);
    },

    init_data() {
        this.setData({
            uid: App.globalData.uid,
            userInfo: App.globalData.userInfo,
            avatar_url: App.globalData.fulluserInfo?.avatar || defaultAvatarUrl,
            user_name: App.globalData.fulluserInfo?.name || '游客',
            fullUserInfo: App.globalData.fulluserInfo,
            mobile: App.globalData.mobile,
            isVip: App.globalData.isVip
        })
    },

    setDefaultAvatar() {
        this.setData({
            avatar_url: defaultAvatarUrl
        })
    },

    get_address_list() {
        let params = {
            uid: this.data.uid
        }
        request.post(api.addresslist, params).then(res => {

            if (!res) {
                this.setData({
                    aid: '',
                })
            }

            // 查找是否有默认地址
            for (let i of res) {
                if (i.is_default) {
                    this.setData({
                        aid: i.id,
                        if_address: true
                    })
                    return
                }
            }
            // 如果地址列表里有地址但没有默认的
            if (this.data.if_address == false) {
                this.setData({
                    aid: res[0].id,
                })
            }
        })
    },

    // 协议勾选回调
    selecting(e) {
        this.setData({
            if_read: !this.data.if_read
        })
    },

    // 切换会员购买框
    select_combo(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            chosen_index: index,
            amount: e.currentTarget.dataset.price,
            vipGoodId: e.currentTarget.dataset.goodid
        })
    },

    // 点击购买回调
    buying_vip() {
        if (!this.data.if_read) {
            util.showToast('请先阅读并同意会员协议')
            return
        }

        // 如果没有授权手机号，拉起授权
        if (!App.globalData.mobile) {
            this.setData({
                visible: true
            })
        } else {
            // 授权了直接拉起微信支付
            this.paying()
        }

        // this.onGetPhoneNumber()
        // App.getMyFullInfo()
        // this.paying()
        // App.confirmSetPhone()
    },

    // 自定义弹出层取消按钮回调
    cancelMethod() {
        this.setData({
            visible: false
        })
    },

    // 自定义弹出层点击空白处显示隐藏回调
    onVisibleChange(e) {
        this.setData({
            visible: e.detail.visible,
        });
    },

    // 手机授权按钮的回调
    async getrealtimePhoneNumber(e) {
        // console.log(e.detail.code)  // 拒绝：undefined 同意：code（和login的code不一样）
        // console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）拒绝：fail user deny 同意：ok
        // console.log(e.detail.errno)  // 错误码（失败时返回）一般情况：undefined  使用次数上限：e.detail.errno===1400001

        // 先隐藏弹出层
        this.setData({
            visible: false
        })

        // 用户同意且未达使用次数上限
        if (e.detail.errno == undefined && e.detail.code) {
            // 成功手机号授权会返回 true
            let phoneflag = await App.setPhone(e.detail.code)
            // 成功后请求用户完整信息
            if (phoneflag) {
                // 成功获取最新完整用户信息
                let fullRes = await App.getMyFullInfo()
                if (fullRes) {
                    this.init_data()
                    this.paying()
                    // console.log('是否有手机号？', this.data.mobile);
                } else {
                    util.showFail('充值超时请稍后重新尝试')
                }
            }
        } else {
            util.showToast('您已取消充值')
        }
    },

    // 调起会员支付，新增会员商品订单。
    // 利用订单号获取微信支付信息，利用支付信息拉起微信支付
    paying() {
        // 运营需要知道充值会员的用户信息，这里自动添加一个默认地址
        // 基本的请求参数信息
        let post_data = {
            uid: this.data.uid,
            aid: this.data.aid,
            type: 1,
            goods_id: this.data.vipGoodId,
        }
        // 开始支付流程
        request.post(api.orderaddv3, post_data).then(res => {
            let post_data = {
                id: res[0]
            }

            request.post(api.orderpay3, post_data).then(res => {
                this.wx_pay(res)
            })
        })
    },

    // 拉起微信支付
    wx_pay(res) {
        const that = this
        let post_data = res
        wx.requestPayment({
            nonceStr: post_data.nonceStr,
            package: post_data.package,
            paySign: post_data.paySign,
            timeStamp: post_data.timeStamp,
            signType: post_data.signType,
            success(res) {
                wx.showLoading({
                    title: '充值成功跳转中',
                })
                let goodid = that.data.vipGoodId
                // console.log("goodid", goodid);
                let trueGrade = -1
                switch (goodid) {
                    case 110:
                        trueGrade = 1
                        break;
                    case 111:
                        trueGrade = 2
                        break;
                    case 112:
                        trueGrade = 3
                        break;
                    default:
                        trueGrade = 1
                        break;
                }
                // 原有会员，保留原级
                let oldGrade = App.globalData.VipGrade
                if (oldGrade >= trueGrade) {
                    trueGrade = oldGrade
                }

                // 记录原过期时间
                let oldEndtime = App.globalData.fulluserInfo.end_time

                let times = 0
                let timerflag = setInterval(async () => {

                    // App.globalData.fulluserInfo = fulluserInfo
                    if (times >= 10) {
                        util.hideLoading()
                        clearInterval(timerflag)
                        util.showFail(
                            "用户信息更新超时，联系客服解决"
                        )
                    }
                    let infoFlag = await App.getMyFullInfo()
                    if (infoFlag) {
                        let vipgrade = App.globalData.VipGrade
                        let newEndtime = App.globalData.fulluserInfo.end_time // 保证充值的时间更新

                        // console.log("vipgrade", vipgrade);
                        if (vipgrade == trueGrade && oldEndtime != newEndtime) {
                            clearInterval(timerflag)
                            util.hideLoading()
                            if (this.from) {
                                wx.navigateTo({
                                    url: this.from,
                                });

                            } else {
                                wx.navigateBack({
                                    delta: 1,
                                })
                            }

                        }
                    } else {
                        util.hideLoading()
                        clearInterval(timerflag)
                        util.showFail(
                            "用户信息更新失败，请联系客服"
                        )
                    }
                    times++
                }, 1000);
            },
            fail(e) {
                util.showToast('您已取消充值');
            }
        })
    },

    onGetPhoneNumber(e) {
        var that = this;
        // getUserProfile
        wx.getUserProfile({
            desc: '用于用户手机号授权', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success(res) {
                console.log(res);
                if (res.code) {
                    console.log('步骤2获检查用户登录状态，获取用户电话号码！', res)
                    wx.request({
                        url: api.set_phone,
                        method: 'POST',
                        data: { code: res.code, uid: that.data.uid },
                        header: { 'content-type': 'application/json' },
                        success: function (res) {
                            console.log("步骤三获取授权码，获取授权openId，session_key", res);
                            var userphone = res.data.data;
                            wx.setStorageSync('userphoneKey', userphone);
                            //解密手机号
                            var msg = e.detail.errMsg;
                            var sessionID = wx.getStorageSync("userphoneKey").session_key;
                            var encryptedData = e.detail.encryptedData;
                            var iv = e.detail.iv;
                            if (msg == 'getPhoneNumber:ok') {//这里表示获取授权成功
                                wx.checkSession({
                                    success: function () {
                                        //这里进行请求服务端解密手机号
                                        that.deciyption(sessionID, encryptedData, iv);
                                    },
                                    fail: function () {
                                        // that.userlogin()
                                    }
                                })
                            }
                        }, fail: function (res) {
                            console.log("fail", res);
                        }
                    })
                } else {
                    console.log('登录失败！' + res.errMsg)
                }
            }
        })
    },

    deciyption(sessionID, encryptedData, iv) {
        var that = this;
        console.log("步骤4根据秘钥解密手机号码sessionID：", sessionID);
        wx.request({
            url: '解密地址',
            data: {
                sessionID: sessionID,
                encryptedData: encryptedData,
                iv: iv
            },
            header: { 'content-type': 'application/json' },
            success: function (res) {
                console.log("79", (res.data.code == 20001));
                if (res.data.code == 20001) {//这里不用管，可以删掉，我的框架里返回值20001是授权失败，可按照自己逻辑处理
                    console.log("获取失败，重新获取", res);
                    that.setData({
                        showPhone: true,
                    })
                } else {
                    console.log("line 79", JSON.parse(res.data.data));
                    var json = JSON.parse(res.data.data);
                    wx.setStorageSync('userphone', JSON.parse(res.data.data).phoneNumber);
                    console.log("步骤5解密成功", res.data.data);
                    that.setData({
                        showPhone: false,
                        "userInfo.phone": wx.getStorageSync('userphone')
                    })
                }

            }, fail: function (res) {
                console.log("fail", res);
            }
        })
    },

    check_register() {
        if (!this.data.islogin) {
            this.get_user_profile()
        }
    },

    get_user_profile() {
        wx.getUserProfile({
            desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
            success: res => {
                App.globalData.userInfo = res.userInfo
                App.globalData.islogin = true
                this.init_data(this.data.options)
                wx.setStorageSync('userInfo', res.userInfo)
            },
            fail: res => {
                console.log(res);
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 检测是否有头像昵称修改
        let isVip = App.globalData.isVip
        let avatarUrl = App.globalData?.fulluserInfo?.avatar
        let nickName = App.globalData?.fulluserInfo?.name
        if (this.data.isVip != isVip || this.data.avatarUrl != avatarUrl || this.data.nickName != nickName) {
            this.init_data()
        }

        // 检测是否有个人信息
        if (!this.data.fullUserInfo?.name && this.data.uid) {
            this.get_myinfo()
        }
    },

    get_myinfo() {
        let params = {
            uid: this.data.uid
        }
        request.post(api.myinfo, params).then(res => {
            this.setData({
                fullUserInfo: res
            })
        })
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})